/*
 * Copyright 2004-2008 the Seasar Foundation and the Others.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 */
package com.yakaten.action;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import net.arnx.jsonic.JSON;
import net.arnx.jsonic.JSONException;

import org.seasar.framework.log.Logger;
import org.seasar.framework.util.ResourceUtil;
import org.seasar.struts.annotation.Execute;

import com.yakaten.dto.KakakuItemInfoDto;
import com.yakaten.dto.KakakuPriceTaskDto;
import com.yakaten.dto.TaskInfoDto;
import com.yakaten.exception.KakakuException;
import com.yakaten.exception.MakeShopException;
import com.yakaten.exception.SystemException;
import com.yakaten.logic.KakakuPriceLogic;
import com.yakaten.logic.TaskInfoLogic;
import com.yakaten.login.MakeShopLogin;
import com.yakaten.service.KakakuItemService;
import com.yakaten.service.KakakuPriceRunner;
import com.yakaten.service.MakeShopItemService;

public class KakakuPriceAction extends BaseAction {
	static Logger logger = Logger.getLogger(KakakuPriceAction.class);

	public String kakakuItemId;
	public String kakakuItemName;
	public String kakakuItemPrice;
	public String shopItemId;
	public String shopItemName;
	public String shopItemPrice;
	public String minPrice;
	public String taskNo;

	public String kakakuSystemRun;
	public String kakakuUserId;
	public String kakakuPassword;
	public String kakakuTime;
	public int status;
	public String quantity;
	public int start;
	public int limit;
	public String kakakuItemSyoryuCalculate;

	public String searchKey;
	public String comparePrice;
	public String compareShopName;

	@Execute(validator = false)
	public String index() {
		return "../kakakuprice.jsp";
	}

//	@Execute(validator = false)
//	public String doReadExistData() throws IOException {
//
//		try {
//			response.getWriter().write(new KakakuPriceLogic().readExistData());
//		} catch (SystemException e) {
//			response.getWriter().write("error");
//		}
//		return null;
//	}

	@Execute(validator = false)
	public String doGetAllTask() throws JSONException, IOException {
		List<KakakuPriceTaskDto> taskList = new ArrayList<KakakuPriceTaskDto>();
		int end = start+limit;
		try {
			taskList = new KakakuPriceLogic().getAllTaskList();
			if(end>taskList.size()){
				end=taskList.size();
			}
		} catch (SystemException e) {
			logger.error(e);
		}
//		response.getWriter().write(
//				"{\"totalCount\":\"" + taskList.size() + "\",\"results\":"
//						+ JSON.encode(taskList.subList(start, end)) + "}");
		response.getWriter().write(
				"{\"totalCount\":\"" + taskList.size() + "\",\"results\":"
						+ JSON.encode(taskList) + "}");
		return null;
	}

	@Execute(validator = false)
	public String doSetKakakuSystemInfo() throws IOException {
		try {
			KakakuPriceRunner.KENKAKU = Integer.parseInt(kakakuTime);
			TaskInfoDto dto = new TaskInfoDto();
			dto.setInfoNo("1");
			dto.setInfoName("kakaku");
			dto.setUserName(kakakuUserId);
			dto.setPassword(kakakuPassword);
			dto.setRunStatus(kakakuSystemRun);
			dto.setSleepTime(Integer.parseInt(kakakuTime));

			TaskInfoLogic logic = new TaskInfoLogic();
			if(logic.getTaskInfo(dto)==null){
				logic.addTaskInfo(dto);
			}else{
				logic.updateTaskInfo(dto);
			}

			response.getWriter().write("success");
		} catch (Exception e) {
			response.getWriter().write("error");
		}
		return null;
	}

	@Execute(validator = false)
	public String doGetKakakuSystemInfo() throws IOException {
		TaskInfoLogic logic = new TaskInfoLogic();
		TaskInfoDto taskInfoDto = new TaskInfoDto();
		taskInfoDto.setInfoNo("1");

		String res="";
		try {
			TaskInfoDto dto =logic.getTaskInfo(taskInfoDto);
			if(dto!=null){
				res=res.concat(dto.getInfoNo()).concat(",")
				.concat(dto.getRunStatus()).concat(",")
				.concat(dto.getUserName()).concat(",")
				.concat(dto.getPassword()).concat(",")
				.concat(""+KakakuPriceRunner.KENKAKU);
			}else{
				res=res.concat("").concat(",")
				.concat("").concat(",")
				.concat("").concat(",")
				.concat("").concat(",")
				.concat(""+KakakuPriceRunner.KENKAKU);
			}
		} catch (SystemException e) {
		}
		response.getWriter().write(res);
		return null;
	}

	@Execute(validator = false)
	public String addTask() throws IOException {
		KakakuPriceLogic logic = new KakakuPriceLogic();
		KakakuPriceTaskDto dto = new KakakuPriceTaskDto();

		try {

			if(logic.isExistTask(kakakuItemId,shopItemId)){
				response.getWriter().write("exist");
				return null;
			}else{
				dto.setTaskNo(logic.getNewTaskNo());
				dto.setKakakuItemId(kakakuItemId);
				dto.setKakakuItemName(kakakuItemName);
				dto.setKakakuItemPrice(Integer.parseInt(kakakuItemPrice));
				dto.setShopItemId(shopItemId);
				dto.setShopItemName(shopItemName);
				dto.setShopItemPrice(Integer.parseInt(shopItemPrice));
				dto.setMinPrice(Integer.parseInt(minPrice));
				dto.setStartPrice(dto.getShopItemPrice());
				dto.setStartTime(new Date());
				dto.setStatus(1);
				dto.setQuantity(quantity);
				dto.setKakakuItemSyoryuCalculate(kakakuItemSyoryuCalculate);
				dto.setComparePrice(Integer.parseInt(comparePrice));
				dto.setCompareShopName(compareShopName);
				logic.addTask(dto);
			}

		} catch (SystemException e) {
			logger.error(e);
		}

		response.getWriter().write("success");
		return null;
	}

	@Execute(validator = false)
	public String doUpdateTaskStatus() throws IOException {
		KakakuPriceLogic logic = new KakakuPriceLogic();
		try {
			logic.updateTaskStatus(taskNo, status);
		} catch (SystemException e) {
			logger.error(e);
		}
		response.getWriter().write("success");
		return null;
	}

	@Execute(validator = false)
	public String doUpdateTask() throws IOException {
		KakakuPriceLogic logic = new KakakuPriceLogic();
		KakakuPriceTaskDto dto = new KakakuPriceTaskDto();

		try {
			dto.setTaskNo(taskNo);
			dto.setKakakuItemId(kakakuItemId);
			dto.setKakakuItemName(kakakuItemName);
			dto.setKakakuItemPrice(Integer.parseInt(kakakuItemPrice));
			dto.setShopItemId(shopItemId);
			dto.setShopItemName(shopItemName);
			dto.setShopItemPrice(Integer.parseInt(shopItemPrice));
			dto.setMinPrice(Integer.parseInt(minPrice));
			dto.setStartPrice(dto.getShopItemPrice());
			dto.setStartTime(new Date());
			dto.setStatus(status);
			dto.setQuantity(quantity);
			dto.setKakakuItemSyoryuCalculate(kakakuItemSyoryuCalculate);
			dto.setComparePrice(Integer.parseInt(comparePrice));
			dto.setCompareShopName(compareShopName);
			logic.updateTask(dto);

		} catch (SystemException e) {
			logger.error(e);
		}

		response.getWriter().write("success");
		return null;
	}

	@Execute(validator = false)
	public String doDeleteTask() throws IOException {
		KakakuPriceLogic logic = new KakakuPriceLogic();

		try {
			if(taskNo!=null && taskNo.length()>0){
				String []taskNos = taskNo.split(",");
				for (int i=0;i<taskNos.length;i++){
					logic.deleteTask(taskNos[i]);
				}
			}
		} catch (SystemException e) {
			logger.error(e);
		}


		response.getWriter().write("success");
		return null;
	}

	@Execute(validator = false)
	public String doGetKakakuItemInfo() throws IOException {
		KakakuItemService kakakuItemService = new KakakuItemService();
		try {
			KakakuItemInfoDto dto = kakakuItemService.getItemInfo(kakakuItemId).get(0);
			response.getWriter().write(
					dto.getItemName() + "," + dto.getItemPrice()+ "," + dto.getShopName()+"," + dto.getSyoryu());
		} catch (KakakuException e) {
			logger.error(e);
			response.getWriter().write("取得失敗。");
		}
		return null;
	}

	@Execute(validator = false)
	public String doGetMyShopItemInfo() throws IOException {
		MakeShopLogin login = new MakeShopLogin();
		try {

			String userName = ResourceUtil.getProperties("yakaten.properties")
					.getProperty("makeshop.login.userName.search");
			String passwd = ResourceUtil.getProperties("yakaten.properties")
					.getProperty("makeshop.login.passwd.search");
			login.doLogin(userName, passwd);
			MakeShopItemService service = new MakeShopItemService();
			Map<String, String> valueMap = service.getItemInfo(shopItemId);

			String itemName = service.getBrandName(valueMap);
			String itemPrice = service.getSellPriceMoto(valueMap);
			response.getWriter().write(itemName + "," + itemPrice+ "," + service.getQuantity(valueMap));

		} catch (MakeShopException e) {
			logger.error(e);
			response.getWriter().write("取得失敗。");
		}
		return null;
	}

}
